#include "kbc.h"

int write_kbc_cmd(unsigned data)
{
	return write_kbc(CMD_REG, data);
}

int write_kbc_data(unsigned data)
{
	int tent = 0;
	while(tent < 3){
		if (!write_kbc(DATA_REG, data))
			return ACK;
		
		if (read_kbc() == Resend)
			tent++;
		else
			return -1;
	}
	return Error;
}

int write_aux(unsigned cmd)
{
	int tent = 0;
	while(tent < 3){
		if (!write_kbc_cmd(cmd))
			return ACK;
		
		if (read_kbc() == Resend)
			tent++;
		else
			return -1;
	}
	return Error;
}

int read_kbc(void)
{
	int data, stat, tempo = 0;
	while (tempo < KBC_TIMEOUT){
		stat = inportb(STAT_REG);
		
		if ((stat & OBF) != 0){
			data = inportb(DATA_REG);
			
			if ((stat & (PAR_ERR | TO_ERR)) == 0)
				return data;
			else
				return -1;
		}
		tempo++;
		delay(1);
	}
	return -1;
}

int write_kbc(unsigned adr, unsigned data)
{
	int stat, tempo = 0;
	while(tempo < KBC_TIMEOUT){
		stat = inportb(STAT_REG);
		
		if ((stat & IBF) == 0){
			outportb(adr, data);
			return 0;
		}
		tempo++;
		delay(1);
	}
	return -1;
}

